package web

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mts/log_srv/internal/domain"
	"mts/log_srv/internal/service"
	middleware "mts/log_srv/internal/web/middleware"
	"net/http"
)

type LangLogHandler struct {
	langSvc service.LangService
}

func NewLangLogHandler(langSvc service.LangService) *LangLogHandler {
	return &LangLogHandler{langSvc: langSvc}
}
func (l LangLogHandler) RegisterRoutes(group *gin.RouterGroup) {
	routes := group.Group("/lang").Use(middleware.JWTAuth())
	routes.GET("/:userId", l.FindLandIdWithUseId)
	routes.POST("/", l.UpdateLangByUserId)
}

func (l LangLogHandler) FindLandIdWithUseId(ctx *gin.Context) {
	userId := ctx.Param("userId")
	langId, err := l.langSvc.FindLangByUserId(ctx, userId)
	if err != nil {
		zap.S().Errorf("获取用户语种id失败:%s", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": "400",
			"msg":  "获取语种id失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    "200",
		"lang_id": langId,
	})
}

func (l LangLogHandler) UpdateLangByUserId(ctx *gin.Context) {
	var lan domain.Language
	if err := ctx.ShouldBindJSON(&lan); err != nil || lan.UserId == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}

	err := l.langSvc.UpdateLangByUserId(ctx, lan)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
			"msg":  "操作失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200, "msg": "操作成功",
	})

}
